<template>
  <div class="dashboard-container">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-left">
        <h2 class="welcome-title">欢迎回来，管理员</h2>
        <p class="welcome-subtitle">以下是您的系统概览和关键指标</p>
      </div>
      <div class="welcome-right">
        <el-button-group>
          <el-button icon="el-icon-download" @click="handleExportReport">导出报表</el-button>
          <el-button type="primary" icon="el-icon-plus" @click="handleCreateNew">新建</el-button>
        </el-button-group>
      </div>
    </div>
    
    <!-- 总览数据卡片 -->
    <el-row :gutter="20" class="data-overview">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>总用户数</span>
              <el-tag size="small" type="success">今日 +12</el-tag>
            </div>
          </template>
          <div class="card-body">
            <div class="card-value">{{ overviewData.userCount }}</div>
            <div class="chart-container mini-chart">
              <!-- 这里放迷你图表 -->
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>系统访问量</span>
              <el-tag size="small" type="warning">今日 +152</el-tag>
            </div>
          </template>
          <div class="card-body">
            <div class="card-value">{{ overviewData.todayVisit }}</div>
            <div class="chart-container mini-chart">
              <!-- 这里放迷你图表 -->
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>服务器负载</span>
              <el-tag size="small" type="danger">高峰期</el-tag>
            </div>
          </template>
          <div class="card-body">
            <div class="card-value">42%</div>
            <div class="chart-container mini-chart">
              <!-- 这里放迷你图表 -->
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="data-card">
          <template #header>
            <div class="card-header">
              <span>任务完成率</span>
              <el-tag size="small" type="info">本周</el-tag>
            </div>
          </template>
          <div class="card-body">
            <div class="card-value">95%</div>
            <div class="chart-container mini-chart">
              <!-- 这里放迷你图表 -->
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 自定义仪表盘布局 -->
    <div class="dashboard-settings">
      <el-dropdown>
        <el-button type="primary" icon="Setting">
          仪表盘设置
        </el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item>保存当前布局</el-dropdown-item>
            <el-dropdown-item>重置默认布局</el-dropdown-item>
            <el-dropdown-item>添加图表组件</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>

    <!-- 可拖拽布局的组件 -->
    <el-row :gutter="20" class="dashboard-widgets">
      <el-col :xs="24" :md="16">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <span>系统访问趋势</span>
              <div class="chart-actions">
                <el-radio-group v-model="visitTimeRange" size="small">
                  <el-radio-button label="day">日</el-radio-button>
                  <el-radio-button label="week">周</el-radio-button>
                  <el-radio-button label="month">月</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          <div class="chart-container" style="height: 350px;">
            <!-- 这里放图表组件 -->
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="8">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <span>用户分布</span>
              <div class="chart-actions">
                <el-button size="small" icon="Refresh" circle></el-button>
              </div>
            </div>
          </template>
          <div class="chart-container" style="height: 350px;">
            <!-- 这里放饼图组件 -->
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-row :gutter="20" class="dashboard-widgets">
      <el-col :xs="24" :md="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <span>最近活动</span>
              <div class="chart-actions">
                <el-button size="small" icon="Plus" circle></el-button>
              </div>
            </div>
          </template>
          <div class="activity-timeline">
            <el-timeline>
              <el-timeline-item timestamp="今天 14:30" type="primary">
                <el-card>
                  <h4>系统更新</h4>
                  <p>系统完成了安全更新部署</p>
                </el-card>
              </el-timeline-item>
              <el-timeline-item timestamp="今天 10:15" type="success">
                <el-card>
                  <h4>新用户注册</h4>
                  <p>10名新用户完成了注册</p>
                </el-card>
              </el-timeline-item>
              <el-timeline-item timestamp="昨天 18:45" type="warning">
                <el-card>
                  <h4>系统警告</h4>
                  <p>监测到异常登录尝试</p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
        </el-card>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-card class="chart-card" shadow="hover">
          <template #header>
            <div class="chart-header">
              <span>系统公告</span>
              <div class="chart-actions">
                <el-button size="small" type="primary" plain>查看全部</el-button>
              </div>
            </div>
          </template>
          <div class="notice-list">
            <el-table :data="noticeList" style="width: 100%" :show-header="false">
              <el-table-column width="50">
                <template #default="scope">
                  <el-avatar :size="30" icon="Bell" :type="scope.row.type"></el-avatar>
                </template>
              </el-table-column>
              <el-table-column>
                <template #default="scope">
                  <div class="notice-item">
                    <div class="notice-title">{{ scope.row.title }}</div>
                    <div class="notice-time">{{ scope.row.time }}</div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOverviewData, getTrendData, getSystemNotices as getNotices, getTodoTasks as getTodos } from '@/api/dashboard'

const router = useRouter()

// 访问时间范围
const visitTimeRange = ref('week')

// 图表引用
const visitChartRef = ref(null)
const userDistributionChartRef = ref(null)

// 概览数据
const overviewData = ref({
  visitCount: 0,
  userCount: 0,
  messageCount: 0,
  orderCount: 0,
  todayVisit: 0,
  todayUser: 0,
  todayMessage: 0,
  todayOrder: 0
})

// 趋势数据
const trendData = ref({
  xAxis: [],
  series: []
})

// 待办任务数据
const todoList = ref([])

// 通知公告数据
const noticeList = ref([])

// 初始化图表
const initCharts = () => {
  // 这里将使用ECharts初始化图表
  // 实际项目中应该引入ECharts并初始化
  console.log('初始化图表')
}

onMounted(() => {
  fetchDashboardData()
  initCharts()
})

// 获取仪表盘数据
const fetchDashboardData = async () => {
  try {
    // 获取概览数据
    const overviewResponse = await getOverviewData({
      timeRange: 'week'
    })
    overviewData.value = overviewResponse.data || overviewData.value

    // 获取趋势数据
    const trendResponse = await getTrendData({
      type: 'visit',
      timeRange: visitTimeRange.value
    })
    trendData.value = trendResponse.data || trendData.value

    // 获取系统通知
    const noticesResponse = await getNotices({
      count: 5
    })
    noticeList.value = noticesResponse.data || []

    // 获取待办任务
    const todosResponse = await getTodos()
    todoList.value = todosResponse.data || []
  } catch (error) {
    console.error('获取仪表盘数据失败', error)
    ElMessage.error('获取仪表盘数据失败')
  }
}

// 时间范围变化处理
const handleTimeRangeChange = async () => {
  try {
    // 获取新的趋势数据
    const trendResponse = await getTrendData({
      type: 'visit',
      timeRange: visitTimeRange.value
    })
    trendData.value = trendResponse.data || trendData.value
    
    // 更新图表
    // 根据实际图表库更新
  } catch (error) {
    console.error('获取趋势数据失败', error)
    ElMessage.error('获取趋势数据失败')
  }
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case '已完成':
      return 'success'
    case '处理中':
      return 'warning'
    case '已取消':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取活动图标
const getActivityIcon = (type) => {
  switch (type) {
    case 'user':
      return 'el-icon-user'
    case 'order':
      return 'el-icon-shopping-cart-full'
    case 'system':
      return 'el-icon-setting'
    case 'alert':
      return 'el-icon-warning'
    default:
      return 'el-icon-bell'
  }
}

// 获取通知类型标签
const getNoticeTypeTag = (type) => {
  return type === '1' ? 'primary' : 'success'
}

// 获取通知类型标签文本
const getNoticeTypeLabel = (type) => {
  return type === '1' ? '通知' : '公告'
}

// 判断是否为新通知（3天内）
const isNewNotice = (createTime) => {
  const now = new Date()
  const createDate = new Date(createTime)
  const diffTime = Math.abs(now - createDate)
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return diffDays <= 3
}

// 跳转到通知公告页面
const navigateToNotice = () => {
  router.push('/system/notice')
}

// 查看通知详情
const viewNotice = (notice) => {
  // 显示通知详情对话框
  ElMessageBox.alert(
    `<div class="notice-detail">
      <div class="notice-detail-header">
        <h3>${notice.noticeTitle}</h3>
        <div class="notice-meta">
          <span>发布人: ${notice.createBy}</span>
          <span>发布时间: ${notice.createTime}</span>
        </div>
      </div>
      <div class="notice-detail-content">
        ${notice.noticeContent}
      </div>
    </div>`,
    notice.noticeType === '1' ? '通知详情' : '公告详情',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭',
      customClass: 'notice-detail-dialog'
    }
  )
}

// 获取通知公告列表
const fetchNoticeList = async () => {
  // 这里可以通过API获取实际的通知公告数据
  // noticeList.value = await getNotices()
}

// 导出报表
const handleExportReport = () => {
  ElMessageBox.confirm('确定要导出当前报表数据吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info'
  }).then(() => {
    // 模拟导出报表
    ElMessage({
      type: 'success',
      message: '报表导出成功，请在系统通知中查看下载链接',
      duration: 2000
    })
    
    // 添加一条通知消息
    setTimeout(() => {
      ElMessage({
        type: 'info',
        message: '报表文件已生成，可以在消息中心查看',
        duration: 3000
      })
    }, 2000)
  }).catch(() => {})
}

// 新建菜单
const handleCreateNew = () => {
  // 显示新建选项菜单
  ElMessageBox.alert(
    `<div class="create-options">
      <div class="create-option" @click="createOrder">
        <i class="el-icon-shopping-cart-full"></i>
        <span>新建订单</span>
      </div>
      <div class="create-option" @click="createUser">
        <i class="el-icon-user"></i>
        <span>新建用户</span>
      </div>
      <div class="create-option" @click="createProduct">
        <i class="el-icon-goods"></i>
        <span>新建产品</span>
      </div>
      <div class="create-option" @click="createArticle">
        <i class="el-icon-document"></i>
        <span>新建文章</span>
      </div>
    </div>`,
    '选择创建类型',
    {
      dangerouslyUseHTMLString: true,
      showCancelButton: false,
      confirmButtonText: '关闭',
      customClass: 'create-dialog'
    }
  )
  
  // 添加点击事件（实际项目中应该使用更优雅的方式）
  setTimeout(() => {
    const options = document.querySelectorAll('.create-option')
    options.forEach(option => {
      option.style.cursor = 'pointer'
      option.style.padding = '15px'
      option.style.display = 'flex'
      option.style.alignItems = 'center'
      option.style.borderBottom = '1px solid #f0f0f0'
      
      option.addEventListener('click', function() {
        const action = this.getAttribute('data-action') || this.getAttribute('@click')
        if (action === 'createOrder') {
          ElMessage.info('创建订单功能开发中...')
        } else if (action === 'createUser') {
          ElMessage.info('创建用户功能开发中...')
        } else if (action === 'createProduct') {
          ElMessage.info('创建产品功能开发中...')
        } else if (action === 'createArticle') {
          ElMessage.info('创建文章功能开发中...')
        }
        document.querySelector('.el-message-box__close').click()
      })
    })
  }, 100)
}

// 导航到订单列表
const navigateToOrders = () => {
  ElMessage.info('订单管理功能开发中...')
  // 实际项目中应该跳转到订单列表页面
  // router.push('/orders')
}

// 导航到活动列表
const navigateToActivities = () => {
  ElMessage.info('活动管理功能开发中...')
  // 实际项目中应该跳转到活动列表页面
  // router.push('/activities')
}
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
}

/* 欢迎区域样式 */
.welcome-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.welcome-title {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 8px;
  color: #1A2634;
}

.welcome-subtitle {
  font-size: 14px;
  color: #666;
  margin: 0;
}

/* 总览数据卡片样式 */
.data-overview {
  margin-bottom: 20px;
}

.data-card {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-body {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-value {
  font-size: 24px;
  font-weight: bold;
}

/* 自定义仪表盘布局样式 */
.dashboard-settings {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

/* 可拖拽布局的组件样式 */
.dashboard-widgets {
  margin-bottom: 20px;
}

.chart-card {
  margin-bottom: 20px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart-actions {
  display: flex;
  align-items: center;
}

.activity-timeline {
  padding: 10px;
  max-height: 350px;
  overflow-y: auto;
}

.notice-list {
  padding: 10px;
}

.notice-item {
  display: flex;
  flex-direction: column;
}

.notice-title {
  font-size: 14px;
}

.notice-time {
  font-size: 12px;
  color: #999;
}

/* 通知详情样式 */
:deep(.notice-detail-dialog) {
  width: 600px;
}

:deep(.notice-detail-dialog .el-message-box__content) {
  padding: 20px;
}

:deep(.notice-detail) {
  text-align: left;
}

:deep(.notice-detail-header) {
  margin-bottom: 20px;
}

:deep(.notice-detail-header h3) {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 18px;
  font-weight: 600;
  color: #1A2634;
}

:deep(.notice-meta) {
  display: flex;
  justify-content: space-between;
  color: #909399;
  font-size: 14px;
}

:deep(.notice-detail-content) {
  line-height: 1.6;
  color: #606266;
  white-space: pre-line;
}
</style> 